package services

import (
	"GOPAAS/internal/app/global"
	"GOPAAS/internal/app/model"
	"GOPAAS/internal/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"reflect"
	"time"
)

type NewsService struct {
	model.CmsNews
}

func GetNewsService(nid int64) *NewsService {
	db = getDB()
	var news model.CmsNews
	if nid > 0 {
		db.First(&news, nid)
	}
	return &NewsService{news}
}

type NewsItem struct {
	Id                    int64    `json:"id"`
	Title                 string   `json:"title"`
	STitle                string   `json:"s_title"`
	NaviContentTf         string   `json:"naviContentTf"`
	Comments              int64    `json:"comments"`
	Collects              int64    `json:"collects"`
	Praises               int64    `json:"praises"`
	CreateDate            string   `json:"create_date"`
	DateBeauty            string   `json:"date_beauty"`
	Images                string   `json:"images"`
	CoverImages           []string `json:"cover_images"`
	Vurl                  string   `json:"vurl"`
	CategName             string   `json:"categ_name"`
	Content               string   `json:"content"`
	Author                string   `json:"author"`
	HeaderImg             string   `json:"header_img"`
	NewspropertyCommtf    bool     `json:"newsproperty_commtf"`    //评论
	NewspropertyRectf1    bool     `json:"newsproperty_rectf1"`    //推荐
	NewspropertyMartf1    bool     `json:"newsproperty_martf1"`    //滚动
	NewspropertyHottf1    bool     `json:"newsproperty_hottf1"`    //热点
	NewspropertyFiltf1    bool     `json:"newsproperty_filtf1"`    //幻灯
	NewspropertyTttf1     bool     `json:"newsproperty_tttf1"`     //头条
	NewspropertyCarefully bool     `json:"newsproperty_carefully"` //精选
	IsPlacement           bool     `json:"is_placement"`           //置顶
	NewspropertyAnntf1    bool     `json:"newsproperty_anntf1"`    //公告
	NewspropertyJctf1     bool     `json:"newsproperty_jctf1"`     //精彩
	AppStyle              string   `json:"app_style"`
	IsCollect             bool     `json:"is_collect"`
	IsPraise              bool     `json:"is_praise"` //点赞
	Souce                 string   `json:"souce"`     //来源
}

type NewsInfo struct {
	Title                 string   `json:"title"`
	STitle                string   `json:"s_title"`
	NaviContentTf         string   `json:"naviContentTf"`
	CreateDate            string   `json:"create_date"`
	CategName             string   `json:"categ_name"`
	Content               string   `json:"content"`
	Comments              int64    `json:"comments"`
	Collects              int64    `json:"collects"`
	Praises               int64    `json:"praises"`
	NewspropertyCommtf    bool     `json:"newsproperty_commtf"`    //评论
	NewspropertyRectf1    bool     `json:"newsproperty_rectf1"`    //推荐
	NewspropertyMartf1    bool     `json:"newsproperty_martf1"`    //滚动
	NewspropertyHottf1    bool     `json:"newsproperty_hottf1"`    //热点
	NewspropertyFiltf1    bool     `json:"newsproperty_filtf1"`    //幻灯
	NewspropertyTttf1     bool     `json:"newsproperty_tttf1"`     //头条
	NewspropertyCarefully bool     `json:"newsproperty_carefully"` //精选
	IsPlacement           bool     `json:"is_placement"`           //置顶
	NewspropertyAnntf1    bool     `json:"newsproperty_anntf1"`    //公告
	NewspropertyJctf1     bool     `json:"newsproperty_jctf1"`     //精彩
	CoverImages           []string `json:"cover_images"`
	AppStyle              string   `json:"app_style"`
	Author                string   `json:"author"`
	HeaderImg             string   `json:"header_img"`
	IsCollect             bool     `json:"is_collect"`
	IsPraise              bool     `json:"is_praise"` //点赞
	ShareUrl              string   `json:"share_url"`
	Souce                 string   `json:"souce"` //来源
}

type NewsVideoItem struct {
	Id            int64  `json:"id"`
	Title         string `json:"title"`
	STitle        string `json:"s_title"`
	NaviContentTf string `json:"naviContentTf"`
	Comments      int64  `json:"comments"`
	Collects      int64  `json:"collects"`
	Praises       int64  `json:"praises"`
	CreateDate    string `json:"create_date"`
	DateBeauty    string `json:"date_beauty"`
	Vurl          string `json:"vurl"`
	CategName     string `json:"categ_name"`
	Content       string `json:"content"`
	Author        string `json:"author"`
	HeaderImg     string `json:"header_img"`
	IsCollect     bool   `json:"is_collect"`
	IsPraise      bool   `json:"is_praise"` //点赞
	Souce         string `json:"souce"`     //来源
}

func GetNewsList(c *gin.Context, request global.NewsListReq, login_user_id int64, page int, limit int) (result []NewsItem, err error) {
	lang, _ := c.Get("lang")
	var news []model.CmsNews
	offset := (page - 1) * limit
	db = getDB()
	q := db.Model(&model.CmsNews{}).Where("state=?", "已发布")
	p_db := db
	for _, req := range request.Item {
		s_db := db
		value := reflect.ValueOf(req)
		var typeInfo = reflect.TypeOf(req)
		var valInfo = reflect.ValueOf(req)
		for num := 0; num < value.NumField(); num++ {
			key := typeInfo.Field(num).Name
			if key == "Operate" {
				continue
			}
			val := valInfo.Field(num).Bool()
			tag := typeInfo.Field(num).Tag.Get("json")
			if val {
				if req.Operate {
					s_db = s_db.Where(tag+"=?", val)
				} else {
					s_db = s_db.Or(tag+"=?", val)
				}

			}
		}
		if request.Operate {
			p_db = p_db.Where(s_db)
		} else {
			p_db = p_db.Or(s_db)
		}
	}
	q.Where(p_db)
	q.Preload("Categ").Preload("User").Preload("User.Partner").Offset(offset).Limit(limit).Order("is_placement desc,newsproperty_rectf1 desc,sequence desc,create_date desc").Find(&news)
	for _, v := range news {
		var comm int64
		db.Model(&model.CmsNewsComment{}).Where("comment_id=?", v.Id).Count(&comm)
		var images string
		var images1 string
		var images2 string
		var images3 string
		attch_service := GetAttachService(0)
		_, err0 := attch_service.GetAttach("cms.news", v.Id, "images")
		if err0 == nil {
			images = GetSimpleImage("cms.news", v.Id, "images")
		}
		_, err1 := attch_service.GetAttach("cms.news", v.Id, "images1")
		if err1 == nil {
			images1 = GetSimpleImage("cms.news", v.Id, "images1")
		}
		_, err2 := attch_service.GetAttach("cms.news", v.Id, "images2")
		if err2 == nil {
			images2 = GetSimpleImage("cms.news", v.Id, "images2")
		}
		_, err3 := attch_service.GetAttach("cms.news", v.Id, "images3")
		if err3 == nil {
			images3 = GetSimpleImage("cms.news", v.Id, "images3")
		}
		var cover_images = make([]string, 0)
		switch v.AppStyle.String {
		case "右图左文本":
			fallthrough
		case "左图右文本":
			fallthrough
		case "上标题下一图":
			fallthrough
		case "上一图下标题":
			cover_images = []string{images1}
		case "上标题下三图":
			cover_images = []string{images1, images2, images3}
		}
		result = append(result, NewsItem{
			Id:                    v.Id,
			Title:                 v.Name,
			NaviContentTf:         v.NaviContentTf.String,
			Comments:              comm,
			CreateDate:            v.CreateDate.Format("2006-01-02 15:04:05"),
			DateBeauty:            utils.BeautifyDate(v.CreateDate),
			Images:                images,
			CoverImages:           cover_images,
			CategName:             utils.GetJsonName(v.Categ.Name, lang.(string)),
			Vurl:                  v.Vurl.String,
			NewspropertyRectf1:    v.NewspropertyRectf1.Bool,
			NewspropertyMartf1:    v.NewspropertyMartf1.Bool,
			NewspropertyHottf1:    v.NewspropertyHottf1.Bool,
			NewspropertyFiltf1:    v.NewspropertyFiltf1.Bool,
			NewspropertyTttf1:     v.NewspropertyTttf1.Bool,
			NewspropertyCarefully: v.NewspropertyCarefully.Bool,
			IsPlacement:           v.IsPlacement.Bool,
			NewspropertyAnntf1:    v.NewspropertyAnntf1.Bool,
			NewspropertyJctf1:     v.NewspropertyJctf1.Bool,
			AppStyle:              v.AppStyle.String,
			Author:                v.User.Partner.Name,
			IsCollect:             GetNewsService(v.Id).IsCollect(login_user_id),
			IsPraise:              GetNewsService(v.Id).IsPraise(login_user_id),
		})
	}
	return
}
func GetNewsVideoList(categ_id int64, login_user_id int64, tab string, page int, limit int) (result []NewsVideoItem, err error) {
	var news []model.CmsNews
	offset := (page - 1) * limit
	db = getDB()
	q := db.Model(&model.CmsNews{}).Where("state=? and vurl<>''", "已发布")
	if tab != "" {
		q.Where(tab+"=?", true)
	}
	if categ_id > 0 {
		q.Where("categ_id=?", categ_id)
	}
	q.Preload("Categ").Preload("User").Preload("User.Partner").Preload("Souce").Offset(offset).Limit(limit).Order("is_placement desc,newsproperty_rectf1 desc,sequence desc,create_date desc").Find(&news)
	for _, v := range news {
		news_service := GetNewsService(v.Id)
		result = append(result, NewsVideoItem{
			Id:            v.Id,
			Title:         v.Name,
			NaviContentTf: v.NaviContentTf.String,
			Comments:      news_service.getCommentNums(),
			Collects:      news_service.getCollectNums(),
			Praises:       news_service.getPraiseNums(),
			CreateDate:    v.CreateDate.Format("2006-01-02 15:04:05"),
			DateBeauty:    utils.BeautifyDate(v.CreateDate),
			CategName:     v.Categ.Name,
			Vurl:          v.Vurl.String,
			Author:        v.User.Partner.Name,
			HeaderImg:     GetImage(128, "res.partner", v.User.PartnerId),
			IsCollect:     news_service.IsCollect(login_user_id),
			IsPraise:      news_service.IsPraise(login_user_id),
			Souce:         v.Souce.Name,
		})
	}
	return
}

// GetNewsCollectList 收藏列表
func GetNewsCollectList(c *gin.Context, categ_id int64, login_user_id int64, page int, limit int) (result []NewsItem, err error) {
	var news []model.CmsNews
	lang, _ := c.Get("lang")
	offset := (page - 1) * limit
	db = getDB()
	q := db.Model(&model.CmsNews{}).Joins("right join cms_news_follows_rel on cms_news.id=cms_news_follows_rel.cms_id").Where("cms_news_follows_rel.user_id=? and state=?", login_user_id, "已发布")
	if categ_id > 0 {
		q.Where("categ_id=?", categ_id)
	}
	q.Preload("Categ").Preload("User").Preload("User.Partner").Preload("Souce").Offset(offset).Limit(limit).Order("create_date desc").Find(&news)
	for _, v := range news {
		var images string
		_, err0 := GetAttachService(0).GetAttach("cms.news", v.Id, "images")
		if err0 == nil {
			images = GetSimpleImage("cms.news", v.Id, "images")
		}
		news_service := GetNewsService(v.Id)
		result = append(result, NewsItem{
			Id:                    v.Id,
			Title:                 v.Name,
			NaviContentTf:         v.NaviContentTf.String,
			Comments:              news_service.getCommentNums(),
			Collects:              news_service.getCollectNums(),
			Praises:               news_service.getPraiseNums(),
			CreateDate:            v.CreateDate.Format("2006-01-02 15:04:05"),
			DateBeauty:            utils.BeautifyDate(v.CreateDate),
			Images:                images,
			CoverImages:           news_service.getCoverImages(),
			CategName:             utils.GetJsonName(v.Categ.Name, lang.(string)),
			Vurl:                  v.Vurl.String,
			NewspropertyCommtf:    v.NewspropertyCommtf.Bool,
			NewspropertyRectf1:    v.NewspropertyRectf1.Bool,
			NewspropertyMartf1:    v.NewspropertyMartf1.Bool,
			NewspropertyHottf1:    v.NewspropertyHottf1.Bool,
			NewspropertyFiltf1:    v.NewspropertyFiltf1.Bool,
			NewspropertyTttf1:     v.NewspropertyTttf1.Bool,
			NewspropertyCarefully: v.NewspropertyCarefully.Bool,
			IsPlacement:           v.IsPlacement.Bool,
			NewspropertyAnntf1:    v.NewspropertyAnntf1.Bool,
			NewspropertyJctf1:     v.NewspropertyJctf1.Bool,
			AppStyle:              v.AppStyle.String,
			Author:                v.User.Partner.Name,
			HeaderImg:             GetImage(128, "res.partner", v.User.PartnerId),
			IsCollect:             news_service.IsCollect(login_user_id),
			IsPraise:              news_service.IsPraise(login_user_id),
			Souce:                 v.Souce.Name,
		})
	}
	return
}

// getCoverImages 获取新闻列表图片
func (n *NewsService) getCoverImages() []string {
	var images1 string
	var images2 string
	var images3 string
	attach_service := GetAttachService(0)
	_, err1 := attach_service.GetAttach("cms.news", n.Id, "images1")
	if err1 == nil {
		images1 = GetSimpleImage("cms.news", n.Id, "images1")
	}
	_, err2 := attach_service.GetAttach("cms.news", n.Id, "images2")
	if err2 == nil {
		images2 = GetSimpleImage("cms.news", n.Id, "images2")
	}
	_, err3 := attach_service.GetAttach("cms.news", n.Id, "images3")
	if err3 == nil {
		images3 = GetSimpleImage("cms.news", n.Id, "images3")
	}
	var cover_images = make([]string, 0)
	switch n.AppStyle.String {
	case "右图左文本":
		fallthrough
	case "左图右文本":
		fallthrough
	case "上标题下一图":
		fallthrough
	case "上一图下标题":
		cover_images = []string{images1}
	case "上标题下三图":
		cover_images = []string{images1, images2, images3}
	}
	return cover_images
}

// getCommentNums 获取新闻评论数量
func (n *NewsService) getCommentNums() int64 {
	var comm int64
	db.Model(&model.CmsNewsComment{}).Where("comment_id=?", n.Id).Count(&comm)
	return comm
}

// getCollectNums 获取新闻收藏数量
func (n *NewsService) getCollectNums() int64 {
	var comm int64
	db.Model(&model.CmsNewsFollowsRel{}).Where("cms_id=?", n.Id).Count(&comm)
	return comm
}

// getPraiseNums 获取新闻点赞数量
func (n *NewsService) getPraiseNums() int64 {
	var comm int64
	db.Model(&model.CmsPraise{}).Where("order_id=?", n.Id).Count(&comm)
	return comm
}

// GetInfo 新闻详情
func (n *NewsService) GetInfo(c *gin.Context, login_user_id int64) (res NewsInfo, err error) {
	db = getDB()
	lang, _ := c.Get("lang")
	user_service := GetUserService(n.UserId.Int64)
	user, _ := user_service.GetUserInfo()
	res.Title = n.Name
	res.NaviContentTf = n.NaviContentTf.String
	res.Comments = n.getCommentNums()
	res.Collects = n.getCollectNums()
	res.Praises = n.getPraiseNums()
	res.CreateDate = n.CreateDate.Format("2006-01-02 15:04:05")
	res.CoverImages = n.getCoverImages()
	var categ model.CmsCategory
	db.First(&categ, n.CategId)
	var souce model.CmsSouce
	db.First(&souce, n.SouceId)
	res.CategName = utils.GetJsonName(categ.Name, lang.(string))
	res.NewspropertyCommtf = n.NewspropertyCommtf.Bool
	res.NewspropertyRectf1 = n.NewspropertyRectf1.Bool
	res.NewspropertyMartf1 = n.NewspropertyMartf1.Bool
	res.NewspropertyHottf1 = n.NewspropertyHottf1.Bool
	res.NewspropertyFiltf1 = n.NewspropertyFiltf1.Bool
	res.NewspropertyTttf1 = n.NewspropertyTttf1.Bool
	res.NewspropertyCarefully = n.NewspropertyCarefully.Bool
	res.IsPlacement = n.IsPlacement.Bool
	res.NewspropertyAnntf1 = n.NewspropertyAnntf1.Bool
	res.NewspropertyJctf1 = n.NewspropertyJctf1.Bool
	res.Content = n.Content.String
	res.AppStyle = n.AppStyle.String
	res.Author = user.Name
	res.HeaderImg = user.Image128
	res.IsCollect = n.IsCollect(login_user_id)
	res.IsPraise = n.IsPraise(login_user_id)
	res.ShareUrl = fmt.Sprintf("/h5/news/detail/%d", n.Id)
	res.Souce = souce.Name
	return
}

// Collect 收藏/取消新闻
func (n *NewsService) Collect(user_id int64, status int) (err error) {
	db = getDB()
	var re model.CmsNewsFollowsRel
	result := db.Where("cms_id=? and user_id=?", n.Id, user_id).First(&re)
	if status == 1 && result.RowsAffected == 0 {
		re.CmsId = n.Id
		re.UserId = user_id
		err = db.Create(&re).Error
	}
	if status == 0 {
		err = db.Where("cms_id=? and user_id=?", n.Id, user_id).Delete(&re).Error
	}
	return
}

// IsCollect 是否收藏
func (n *NewsService) IsCollect(user_id int64) (res bool) {
	db = getDB()
	var re model.CmsNewsFollowsRel
	result := db.Where("cms_id=? and user_id=?", n.Id, user_id).First(&re)
	if result.RowsAffected > 0 {
		res = true
	}
	return
}

// Praise 点赞/取消点赞
func (n *NewsService) Praise(user_id int64, status int) (err error) {
	db = getDB()
	var re model.CmsPraise
	result := db.Where("order_id=? and user_id=?", n.Id, user_id).First(&re)
	if status == 1 && result.RowsAffected == 0 {
		var user model.ResUsers
		db.Preload("Partner").First(&user, user_id)
		re.OrderId = n.Id
		re.Name = user.Partner.Name
		re.CreateDate = time.Now()
		re.UserId = user_id
		err = db.Create(&re).Error
	}
	if status == 0 {
		err = db.Where("order_id=? and user_id=?", n.Id, user_id).Delete(&re).Error
	}
	return
}

// IsPraise 是否点赞
func (n *NewsService) IsPraise(user_id int64) (res bool) {
	db = getDB()
	var re model.CmsPraise
	result := db.Where("order_id=? and user_id=?", n.Id, user_id).First(&re)
	if result.RowsAffected > 0 {
		res = true
	}
	return
}

// Comment 评论
func (n *NewsService) Comment(login_user_id int64, parent_id int64, comment string) (err error) {
	db = getDB()
	var comm model.CmsNewsComment
	comm.CommentId = n.Id
	comm.UserId = login_user_id
	comm.ParentId = utils.NullInt64Value(parent_id)
	comm.Comment = comment
	comm.CreateUid = login_user_id
	comm.WriteUid = login_user_id
	err = db.Select("CommentId", "UserId", "ParentId", "Comment", "CreateUid", "WriteUid").Save(&comm).Error
	return
}

type CommentChildItem struct {
	Id         int64  `json:"id"`
	Comment    string `json:"comment"`
	Author     string `json:"author"`
	HeaderImg  string `json:"header_img"`
	Date       string `json:"date"`
	DateBeauty string `json:"date_beauty"`
}
type CommentItem struct {
	Id         int64  `json:"id"`
	Comment    string `json:"comment"`
	Author     string `json:"author"`
	HeaderImg  string `json:"header_img"`
	Date       string `json:"date"`
	DateBeauty string `json:"date_beauty"`
	//ParentId      int64  `json:"parent_id"`
	//ParentComment string `json:"parent_comment"`
	CommentNums int                `json:"comment_nums"`
	Children    []CommentChildItem `json:"children"`
}

// CommentLists 新闻评论
func (n *NewsService) CommentLists(comment_id int64, page int, limit int) (result []CommentItem, err error) {
	db = getDB()
	var comments []model.CmsNewsComment
	offset := (page - 1) * limit
	q := db.Where("comment_id=?", n.Id)
	if comment_id > 0 {
		q.Where("parent_id=?", comment_id)
	} else {
		q.Where("parent_id is null")
	}
	q.Preload("Parent").Preload("User").Preload("User.Partner").Order("create_date desc").Offset(offset).Limit(limit).Find(&comments)
	for _, v := range comments {
		var childs []model.CmsNewsComment
		var child_item = make([]CommentChildItem, 0)
		db.Preload("User").Preload("User.Partner").Model(&model.CmsNewsComment{}).Where("parent_id=?", v.Id).Order("create_date desc").Find(&childs)
		for _, vv := range childs {
			child_item = append(child_item, CommentChildItem{
				Id:         vv.Id,
				Comment:    vv.Comment,
				Author:     vv.User.Partner.Name,
				Date:       vv.CreateDate.Format("2006-01-02 15:04:05"),
				DateBeauty: utils.BeautifyDate(vv.CreateDate),
			})
		}
		result = append(result, CommentItem{
			Id:          v.Id,
			Comment:     v.Comment,
			Author:      v.User.Partner.Name,
			HeaderImg:   GetImage(128, "res.partner", v.User.PartnerId),
			Date:        v.CreateDate.Format("2006-01-02 15:04:05"),
			DateBeauty:  utils.BeautifyDate(v.CreateDate),
			CommentNums: len(childs),
			Children:    child_item,
		})
	}
	return
}
